import 'dart:async';
import 'dart:convert';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import '../../base/imageres.dart';
import '../../base/constant.dart';
import '../../base/eventbus.dart';
import '../../base/log.dart';
import '../../base/stringres.dart';
import '../../base/theme.dart';
import '../../database/app_data.dart';
import '../../native/nativechannel.dart';
import '../../util/physiological_cycle_count.dart';
import '../../util/string_util.dart';
import '../../views/chart/draw_empty_barchart_widget.dart';
import '../../views/chart/draw_hr_barchart_widget.dart';
import '../../views/chart/draw_hrv_barchart_widget.dart';
import '../../views/chart/draw_temp_barchart_widget.dart';
import '../../views/cycle_painter.dart';
import '../../views/horizontal_line.dart';
import '../../views/jsw_base_view.dart';
import '../../views/wheelview/clickable_list_wheel_widget.dart';

///女性健康的主界面设置
class MainHealthPage extends StatefulWidget {
  const MainHealthPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MainHealthPageState();
  }
}

class _MainHealthPageState extends State<MainHealthPage> {
  static const _tag = '[page_main_health.dart][_MainHealthPageState]';

  StreamSubscription? _bus;

  ///初始化多语言
  bool _initLang = false;

  ///周一到周日日期
  List<DateTime> _weekDates = [];

  ///今天的日期
  final DateTime _todayDate = DateTime.now();

  ///今天的周期(1:月经期 2:卵泡期 3:易孕期(排卵期) 4:排卵日 5:黄体期)
  int _todayFemaleCycle = 1;

  ///周期天数
  int _dayByFemaleCycle = 0;

  ///距离下一个周期天数
  int _distanceFemaleCycle = 0;

  ///距离排卵日天数
  int _distanceOvulationDays = 0;

  ///今天星期几
  int _weekday = 1;

  ///生理周期的值
  var _cycleValue = 0;

  ///生理周期是否规律
  var _regularly = 1;

  ///女性健康目标值(周期跟踪 受孕)
  var _tracking = 1;

  ///最近一次月经的DateTime
  DateTime _menstrualDateTime = DateTime.now();

  ///最近一次月经的时间戳
  int _menstrualTime = 0;

  ///月经期天数
  var _menstrualPeriodDays = 0;

  ///卵泡期天数
  var _follicularPhaseDays = 0;

  ///易孕期(排卵期)天数(最多十天)
  var _easyPregnancyDays = 0;

  ///黄体期天数
  var _lutealPhaseDays = 13;

  ///是否显示排卵日
  bool _isShowOvulation = false;

  ///排卵日
  DateTime _ovulationDateTime = DateTime.now();

  ///用户ID
  var _userId = "";

  ///温度数据
  Map<String, double> _temperatureDataMap = {};

  ///心率变异性数据
  Map<String, double> _hrvDataMap = {};

  ///静息心率数据
  Map<String, double> _hrDataMap = {};

  ///今日提示内容
  var _todayReminder = StringRes.menstrual_period_reminder;

  ///温度类型 0：°C 1：°F
  var _tempType = 0;

  ///初始化健康数据
  String initHealthData = "";

  ///修改后健康数据
  String modifyHealthData = "";

  ///是否初始化数据
  bool isInitHealthData = true;

  ///滑动控制器
  final _scrollController = FixedExtentScrollController();

  ///周期选择器数据
  final List<int> _items = List.generate(28, (index) => index + 18);

  ///滑动item高度
  static const double _itemHeight = 50;

  ///是否正常周期
  final ValueNotifier<bool> _isNormalCycle = ValueNotifier(true);

  ///选中温度 1 心率 2 静息 3
  int _selectChartType = 0;

  ///选择皮肤温度
  double _dayTemperature = 0.0;

  ///选择心率变异性
  double _dayHrv = 0.0;

  ///选择静息心率
  double _dayHr = 0.0;

  ///月经周期时间map
  Map<String, int> _periodDataMap = {};

  ///是否进入选择周期界面
  bool isTargetSetting = false;

  @override
  void initState() {
    super.initState();
    _initEventBus();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: SystemUiOverlay.values);
    _weekday = _todayDate.weekday;
    _weekDates = _getCurrentWeekDates();
    Native.initWomenHealthData();
  }

  @override
  void dispose() {
    _cancelEventBus();
    super.dispose();
  }

  ///初始化EventBus
  void _initEventBus() {
    _bus = EventBusUtil.getInstance().on().listen((event) {
      switch (event.runtimeType) {
        case DataEvent:
          DataEvent dataEvent = event;
          switch (dataEvent.type) {
            case HealthDataType.REFRESH_READLANGFINISH:
              DartLog.i(_tag, '多语言加载完成刷新MainHealthPage界面...');
              StringRes.init();
              setState(() {});
              break;
            case HealthDataType.REFRESH_SETTING_CYCLEVALUE:
              if (_cycleValue != dataEvent.data) {
                _cycleValue = dataEvent.data;
                var timeString = DateFormat("yyyy-MM-dd").format(
                    DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
                modifyHealthData =
                    "$timeString,$_cycleValue,$_menstrualPeriodDays,$_regularly,$_tracking";
                _initCalculationPeriodData();
                int selectChartType = _selectChartType;
                _selectChartType = 0;
                setState(() {});
                Future.delayed(const Duration(milliseconds: 100), () {
                  _selectChartType = selectChartType;
                  setState(() {
                  });
                });
              }
              break;
            case HealthDataType.REFRESH_SETTING_PERIODVALUE:
              if (_menstrualPeriodDays != dataEvent.data) {
                _menstrualPeriodDays = dataEvent.data;
                var timeString = DateFormat("yyyy-MM-dd").format(
                    DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
                modifyHealthData =
                    "$timeString,$_cycleValue,$_menstrualPeriodDays,$_regularly,$_tracking";
                _initCalculationPeriodData();
                int selectChartType = _selectChartType;
                _selectChartType = 0;
                setState(() {});
                Future.delayed(const Duration(milliseconds: 100), () {
                  _selectChartType = selectChartType;
                  setState(() {
                  });
                });
              }
              break;
            case HealthDataType.REFRESH_SETTING_REGULARLY:
              _regularly = dataEvent.data;
              var timeString = DateFormat("yyyy-MM-dd")
                  .format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
              modifyHealthData =
                  "$timeString,$_cycleValue,$_menstrualPeriodDays,$_regularly,$_tracking";

            case HealthDataType.REFRESH_SETTING_TARGETVALUE:
              _tracking = dataEvent.data;
              var timeString = DateFormat("yyyy-MM-dd")
                  .format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
              modifyHealthData =
                  "$timeString,$_cycleValue,$_menstrualPeriodDays,$_regularly,$_tracking";

              break;
            case HealthDataType.REFRESH_CURRENT_HEALTH_DATA:
              if(dataEvent.data["periodEmptyMap"] != null){
                _periodDataMap.clear();
              }
              if(dataEvent.data["periodDataMap"] != null){
                _periodDataMap = dataEvent.data["periodDataMap"];
              }
              if(dataEvent.data["menstrualTime"] != null){
                _menstrualTime = dataEvent.data["menstrualTime"];
              }
              _initCalculationPeriodData();
              int selectChartType = _selectChartType;
              _selectChartType = 0;
              setState(() {});
              Future.delayed(const Duration(milliseconds: 100), () {
                _selectChartType = selectChartType;
                setState(() {
                });
              });

              break;
          }
          break;
        case NativeEvent:
          NativeEvent nativeEvent = event;
          switch (nativeEvent.type) {
            case HealthNativeDataType.INIT_WOMEN_HEALTH_DATA:
              if (nativeEvent.data != null && nativeEvent.data.isNotEmpty) {
                isInitHealthData = true;

                _cycleValue = nativeEvent.data["health_cycle_value"];
                _menstrualPeriodDays = nativeEvent.data["health_period_length"];
                _regularly = nativeEvent.data["health_regularly"];
                _tracking = nativeEvent.data["health_tracking"];
                _menstrualTime = DateTime.parse(nativeEvent.data["health_menstrual_time"]).millisecondsSinceEpoch;
                initHealthData =
                    "${nativeEvent.data["health_menstrual_time"]},$_cycleValue,$_menstrualPeriodDays,$_regularly,$_tracking";
                modifyHealthData =
                    "${nativeEvent.data["health_menstrual_time"]},$_cycleValue,$_menstrualPeriodDays,$_regularly,$_tracking";

                DartLog.i(_tag,
                    'REFRESH_NATIVE_HEALTH 初始化周期天数参数_menstrualTime$_menstrualTime ${DateFormat("yyyy-MM-dd").format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime))} _cycleValue：$_cycleValue _menstrualPeriodDays：$_menstrualPeriodDays regularly：$_regularly tracking：$_tracking');
                _weekday = _todayDate.weekday;
                _weekDates = _getCurrentWeekDates();
                _initCalculationPeriodData();
              } else {
                _cycleValue = 10;
                isInitHealthData = false;
              }
              setState(() {});
              break;

            case HealthNativeDataType.READ_USER_ID:
              _userId = nativeEvent.data["token"];
              break;

            case HealthNativeDataType.READ_HEALTH_HISTORY:
              if (nativeEvent.data != null && nativeEvent.data.isNotEmpty) {
                dynamic decodedData = jsonDecode(nativeEvent.data);
                if (decodedData is Map<String, dynamic>) {
                  _periodDataMap = {};
                  for (var entry in decodedData.entries) {
                    if (entry.value is num) {
                      _periodDataMap[entry.key] = entry.value.toInt();
                    } else {
                      DartLog.e(_tag, 'Invalid value type for key ${entry.key}: ${entry.value.runtimeType}');
                    }
                  }
                }
                DartLog.i(_tag, '实际存储月经的时间列表 READ_HEALTH_HISTORY _periodDataMap:${_periodDataMap.toString()}');
              }
              if(_periodDataMap.isNotEmpty){
                _initCalculationPeriodData();
                setState(() {
                });
              }
              break;

            case HealthNativeDataType.READ_TEMPERATURE_DATA: //更新温度数据
              if (nativeEvent.data["temp_type"] != null) {
                _tempType = nativeEvent.data["temp_type"];
              }
              if (nativeEvent.data["data"] != null) {
                DartLog.i(_tag, "READ_TEMPERATURE_DATA 更新温度数据 data : ${nativeEvent.data["data"].toString()}");
                if (Native.HealthDataApp == 1 && GetPlatform.isIOS) {
                  double totalMultiple = 0;
                  int totalNumber = 0;
                  for (int i = 0; i < nativeEvent.data["data"].length; i++) {
                    if(nativeEvent.data["data"][i].toDouble() != 0.0){
                      totalMultiple = totalMultiple + nativeEvent.data["data"][i].toDouble();
                      totalNumber++;
                    }
                  }
                  double multiple = 0.0;
                  if(totalMultiple > 0 && totalNumber > 0){
                     multiple = totalMultiple / totalNumber;
                  }
                  for (int i = 0; i < nativeEvent.data["data"].length; i++) {
                    double tempValue = nativeEvent.data["data"][i].toDouble() == 0.0 ? 0.0 : (nativeEvent.data["data"][i].toDouble() - multiple);
                    tempValue = tempValue.clamp(-5.0, 5.0);
                    _temperatureDataMap[DateFormat("yyyy.MM.dd").format(_todayDate.subtract(Duration(days: nativeEvent.data["data"].length - 1 - i)))] = tempValue;
                  }
                } else {
                  for (int i = 0; i < nativeEvent.data["data"].length; i++) {
                    double tempValue = nativeEvent.data["data"][i].toDouble();
                    tempValue = tempValue.clamp(-5.0, 5.0);
                    _temperatureDataMap[DateFormat("yyyy.MM.dd").format(_todayDate.subtract(Duration(days: nativeEvent.data["data"].length - 1 - i)))] = tempValue;
                  }
                }
                DartLog.i(_tag, 'READ_TEMPERATURE_DATA 更新温度数据_temperatureDataMap：$_temperatureDataMap');
                final todayKey = DateFormat("yyyy.MM.dd").format(_todayDate);
                _dayTemperature = _temperatureDataMap[todayKey] ?? 0.0;
                if(_temperatureDataMap.isNotEmpty){
                  _selectChartType = 1;
                  setState(() {});
                }
              }
              break;

            case HealthNativeDataType.READ_HRV_DATA: //更新心率变异性数据
              if (nativeEvent.data["data"] != null) {
                DartLog.i(_tag,
                    "READ_HRV_DATA 更新心率变异性数据 data type: ${nativeEvent.data.runtimeType}");
                for (int i = 0; i < nativeEvent.data["data"].length; i++) {
                  _hrvDataMap[DateFormat("yyyy.MM.dd").format(
                      _todayDate.subtract(Duration(
                          days: nativeEvent.data["data"].length -
                              1 -
                              i)))] = (nativeEvent.data["data"][i]).toDouble();
                }
                DartLog.i(
                    _tag, 'READ_HRV_DATA 更新心率变异性数据_hrvDataMap：$_hrvDataMap');
                final todayKey = DateFormat("yyyy.MM.dd").format(_todayDate);
                _dayHrv = _hrvDataMap[todayKey] ?? 0;
              }
              break;

            case HealthNativeDataType.READ_HR_DATA: //更新静息心率数据
              if (nativeEvent.data["data"] != null) {
                DartLog.i(_tag,
                    "READ_HR_DATA 更新静息心率数据 data type: ${nativeEvent.data.runtimeType}");
                for (int i = 0; i < nativeEvent.data["data"].length; i++) {
                  _hrDataMap[DateFormat("yyyy.MM.dd").format(
                      _todayDate.subtract(Duration(
                          days: nativeEvent.data["data"].length -
                              1 -
                              i)))] = (nativeEvent.data["data"][i]).toDouble();
                }
                DartLog.i(_tag, 'READ_HR_DATA 更新静息心率数据_hrDataMap：$_hrDataMap');
                final todayKey = DateFormat("yyyy.MM.dd").format(_todayDate);
                _dayHr = _hrDataMap[todayKey] ?? 0;
              }
              break;

            case HealthNativeDataType.SET_WOMEN_CONCEPTION_DATA:
              isTargetSetting = true;
              _tracking = 0;
              setState(() {
              });
              break;
          }
          break;
      }
    });
  }

  ///取消EventBus订阅
  void _cancelEventBus() {
    _bus?.cancel();
  }

  ///更新女性健康数据
  void updateWomanHealthData() {
    DartLog.i(_tag,
        '退出健康界面,= ${initHealthData != modifyHealthData} initHealthData: $initHealthData modifyHealthData: $modifyHealthData ');
    if (initHealthData != modifyHealthData) {
      var timeString = DateFormat("yyyy-MM-dd")
          .format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime));
      APPDatabase.saveWomanHealthData(_userId, timeString, timeString,
              _menstrualPeriodDays, _cycleValue, _regularly, 1)
          .then((value) {
        if (value) {
          DartLog.i(_tag, "服务器更新数据成功....");
        }
      });
    }
  }

  ///周期天数
  List<CycleDay> _days = [];

  ///初始化主界面的周期数据
  void _initCalculationPeriodData() {
    if(_menstrualTime < 0 || _cycleValue <= 0 || _menstrualPeriodDays <= 0){
      return;
    }
    _menstrualDateTime = DateTime.fromMillisecondsSinceEpoch(_menstrualTime);

    DateTime periodStart = _menstrualDateTime;
    int differenceDay = _todayDate.difference(_menstrualDateTime).inDays % _cycleValue;
    if(differenceDay > 0){
      periodStart = _todayDate.subtract(Duration(days: differenceDay));
      DartLog.i(_tag, '_initCalculationPeriodData 重新计算周期 periodStart${DateFormat("yyyy-MM-dd").format(periodStart)} ');
    }

    final cycleCalculator = CycleCalculator(periodStart: periodStart, cycleLength: _cycleValue, periodLength: _menstrualPeriodDays);
    final summary = cycleCalculator.summarize();
    Map<String, int> cycleMap = summary.compute();
    _days = cycleCalculator.generateCycleDays();
    DartLog.i(_tag,
        '_initCalculationPeriodData _days${_days.toString()} ');

    _follicularPhaseDays = cycleMap["卵泡期"]!;
    _easyPregnancyDays = cycleMap["易孕前窗"]! +  cycleMap["排卵日"]! +  cycleMap["易孕后窗"]!;
    _lutealPhaseDays = cycleMap["黄体期"]!;
    _isShowOvulation = cycleMap["排卵日"]! == 1;
    _ovulationDateTime = _menstrualDateTime.add(Duration(days: _menstrualPeriodDays  + _follicularPhaseDays + (cycleMap["易孕前窗"]!)));

    DartLog.i(_tag,
        '_initCalculationPeriodData 初始化周期天数参数_menstrualTime$_menstrualTime ${DateFormat("yyyy-MM-dd").format(DateTime.fromMillisecondsSinceEpoch(_menstrualTime))} _cycleValue：$_cycleValue _menstrualPeriodDays：$_menstrualPeriodDays _follicularPhaseDays：$_follicularPhaseDays _easyPregnancyDays：$_easyPregnancyDays _lutealPhaseDays：$_lutealPhaseDays  ');

    DartLog.i(_tag,
        '_initCalculationPeriodData 排卵日期 _ovulationDateTime ${DateFormat("yyyy-MM-dd").format(_ovulationDateTime)} distanceDays ${_menstrualPeriodDays  + _follicularPhaseDays + (cycleMap["易孕前窗"]!)}');

    _todayFemaleCycle = _getTodayFemaleCycle();
    _dayByFemaleCycle = _getDayByFemaleCycle();
    _distanceFemaleCycle = _getDistanceFemaleCycle();

    if(_periodDataMap.isNotEmpty && _periodDataMap[DateFormat("yyyy-MM-dd").format(_todayDate)] != null && _periodDataMap[DateFormat("yyyy-MM-dd").format(_todayDate)] == 2){
      int toDayDifferenceDay = 1;
      for (int i = 0; i < _periodDataMap.length ; i++) {
        DateTime date = _todayDate.subtract(Duration(days: i));
        if(_periodDataMap[DateFormat("yyyy-MM-dd").format(date)] != null && _periodDataMap[DateFormat("yyyy-MM-dd").format(date)] == 7){
          toDayDifferenceDay = i;
          break;
        }
      }
      strTodayHealthTitle = "${StringRes.follicular_phase} ${StringUtil.formatString(StringRes.what_day, ["$toDayDifferenceDay"])}";
      int differenceDay = periodStart.add(Duration(days: (_menstrualPeriodDays + _follicularPhaseDays))).difference(_todayDate).inDays - 1;
      DartLog.i(_tag, '下一个阶段时间间隔 toDayDifferenceDay $toDayDifferenceDay  differenceDay $differenceDay');
      strTodayHealthContent = StringUtil.formatString(StringRes.female_cycle_content, [differenceDay == 0 ? "1" : differenceDay.toString()]);
    }else{
      strTodayHealthTitle = StringUtil.getTodayHealthTitle(_todayFemaleCycle, _dayByFemaleCycle);
      strTodayHealthContent = StringUtil.getTodayHealthContent(_todayFemaleCycle,_distanceFemaleCycle,_distanceOvulationDays);
    }
    if(_todayFemaleCycle == 3){
      _distanceOvulationDays = cycleMap["易孕前窗"]! - _dayByFemaleCycle;
    }

    DartLog.i(_tag, '_initCalculationPeriodData 计算天数 _todayFemaleCycle $_todayFemaleCycle _dayByFemaleCycle $_dayByFemaleCycle _distanceFemaleCycle$_distanceFemaleCycle _distanceOvulationDays$_distanceOvulationDays');

    Native.writeHealthItemData(strTodayHealthTitle, strTodayHealthContent);
    _loadOvulationImage();
  }

  ///获取当前日期所在周从周一到周日的日期
  List<DateTime> _getCurrentWeekDates() {
    DateTime now = DateTime.now();
    int weekday = now.weekday;
    DateTime lastSunday = now.subtract(Duration(days: weekday));
    List<DateTime> weekDates = [];
    for (int i = 0; i < 7; i++) {
      weekDates.add(lastSunday.add(Duration(days: i)));
    }
    return weekDates;
  }

  /// 预加载的排卵期图片
  ui.Image? _ovulationImage;

  /// 加载排卵期图片资源
  Future<void> _loadOvulationImage() async {
    final data = await rootBundle.load(DateTime.now().millisecondsSinceEpoch >= _ovulationDateTime.millisecondsSinceEpoch ? ImageRes.ic_cycle_ovulation : ImageRes.ic_cycle_ovulation_uncheck);
    final codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
    final frameInfo = await codec.getNextFrame();
    setState(() {
      _ovulationImage = frameInfo.image; // 保存加载后的图片
    });
  }

  ///今天周期标题
  String strTodayHealthTitle = "";

  ///今天周期内容
  String strTodayHealthContent = "";

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(isInitHealthData
                  ? ImageRes.bg_health_main
                  : ImageRes.bg_health_set),
              fit: BoxFit.cover, // 图片填充方式
            ),
          ),
        ),
        isTargetSetting ? _buildTargetSetting():(isInitHealthData
            ? SingleChildScrollView(
          child: Column(
            children: [
              //标题栏
              AppBar(
                elevation: 0.0,
                backgroundColor: Colors.transparent,
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  mainAxisSize: MainAxisSize.max,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      StringRes.women_health_title,
                      textAlign: TextAlign.center,
                      style: ThemeUtil.toolbar,
                    ),
                    IconButton(
                      icon: const ImageIcon(
                        AssetImage(ImageRes.ic_mian_calendar),
                        size: 22,
                        color: Colors.white,
                      ),
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      hoverColor: Colors.transparent,
                      onPressed: () {
                        //日历
                        Get.toNamed(PageIndex.cycleCalendarPage,
                            arguments: {
                              "userId": _userId,
                              "periodDataMap": _periodDataMap,
                              "menstrualTime": _menstrualTime,
                              "cycleValue": _cycleValue,
                              "periodValue": _menstrualPeriodDays,
                              "regularly": _regularly,
                              "tracking": _tracking,
                            });
                      },
                    ),
                  ],
                ),
                leading: IconButton(
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  hoverColor: Colors.transparent,
                  icon: const Icon(
                    Icons.arrow_back,
                    color: Colors.white,
                  ),
                  onPressed: () {
                    updateWomanHealthData();
                    Future.delayed(const Duration(milliseconds: 50), () {
                      Native.backPressed();
                    });
                  },
                ),
                actions: [
                  IconButton(
                    padding: const EdgeInsets.only(right: 20),
                    icon: ImageIcon(
                      AssetImage(ImageRes.ic_mian_history),
                      size: 22,
                      color: Colors.white,
                    ),
                    splashColor: Colors.transparent,
                    highlightColor: Colors.transparent,
                    hoverColor: Colors.transparent,
                    onPressed: () {
                      //历史
                      Get.toNamed(PageIndex.cycleHistoryPage, arguments: {
                        "periodDataMap": _periodDataMap,
                        "menstrualTime": _menstrualTime,
                        "cycleValue": _cycleValue,
                        "periodValue": _menstrualPeriodDays
                      });
                    },
                  ),
                ],
              ),

              //日期设置
              JSWLine(
                clickable: false,
                margin: const EdgeInsets.only(
                    top: 16, left: 12.0, right: 12.0),
                children: [
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 7
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.sunday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[0])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[0]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[0])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[0].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[0])
                              ? Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 1
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.monday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[1])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[1]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[1])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[1].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[1])
                              ? Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 2
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.tuesday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[2])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[2]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[2])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[2].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[2])
                              ? Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 3
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.wednesday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[3])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[3]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[3])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[3].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[3])
                              ? Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 4
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.thursday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[4])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[4]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[4])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[4].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[4])
                              ? Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 5
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.friday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[5])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[5]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[5])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[5].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[5])
                              ? Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                              padding: const EdgeInsets.only(
                                  top: 8, bottom: 4, left: 6, right: 6),
                              decoration: BoxDecoration(
                                color: _weekday == 6
                                    ? Colors.white30
                                    : Colors.transparent,
                                borderRadius:
                                BorderRadius.circular(25.0), // 设置圆角半径
                              ),
                              child: Column(
                                mainAxisAlignment:
                                MainAxisAlignment.start,
                                crossAxisAlignment:
                                CrossAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    StringRes.saturday,
                                    style: ThemeUtil.p2
                                        .copyWith(fontSize: 14),
                                  ),
                                  _isDuringMenstrualPeriodDay(
                                      _weekDates[6])
                                      ? Container(
                                      margin: const EdgeInsets.only(
                                          top: 8),
                                      alignment: Alignment.center,
                                      child: Stack(
                                        alignment: Alignment.center,
                                        children: [
                                          // 背景图
                                          Image.asset(
                                            ImageRes.bg_dashed_circle,
                                            width: 32,
                                            height: 32,
                                            fit: BoxFit.cover,
                                          ),
                                          Positioned(
                                            child: Column(
                                              mainAxisAlignment:
                                              MainAxisAlignment
                                                  .center,
                                              crossAxisAlignment:
                                              CrossAxisAlignment
                                                  .center,
                                              children: [
                                                Text(
                                                  _weekDates[6]
                                                      .day
                                                      .toString(),
                                                  textAlign: TextAlign
                                                      .center,
                                                  style: ThemeUtil.p2
                                                      .copyWith(
                                                      fontSize:
                                                      14),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ))
                                      : Container(
                                    margin: const EdgeInsets.only(
                                        top: 8),
                                    alignment: Alignment.center,
                                    width: 30,
                                    height: 30,
                                    decoration: BoxDecoration(
                                        color: Color(
                                            _getWeekBackgroundColor(
                                                _weekDates[6])),
                                        shape: BoxShape.circle),
                                    child: Text(
                                      _weekDates[6].day.toString(),
                                      textAlign: TextAlign.center,
                                      style: ThemeUtil.p2
                                          .copyWith(fontSize: 14),
                                    ),
                                  ),
                                ],
                              )),
                          const SizedBox(
                            height: 2,
                          ),
                          _isOvulationDay(_weekDates[6])
                              ? const Image(
                            image: AssetImage(
                                ImageRes.ic_main_ovulation),
                            width: 12,
                            height: 12,
                          )
                              : const SizedBox(
                            height: 12,
                          ),
                        ],
                      )),
                ],
              ),

              //显示女性健康类型和日期
              Container(
                margin: const EdgeInsets.only(
                    top: 20, left: 30, right: 30, bottom: 20),
                alignment: Alignment.center,
                child: Stack(
                    alignment: AlignmentDirectional.center,
                    children: [
                      //背景图
                      const Image(
                        image: AssetImage(ImageRes.bg_female_cycle),
                        width: 280,
                        height: 280,
                      ),

                      //中间文字
                      Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SizedBox(
                            width: 200,
                            child: Text(
                              textAlign: TextAlign.center,
                              StringUtil.getTodayHealthDate(_todayDate),
                              style: ThemeUtil.mp2.copyWith(fontSize: 12),
                            ),
                          ),
                          const SizedBox(height: 10),
                          SizedBox(
                            width: 200,
                            child: Text(
                              textAlign: TextAlign.center,
                              strTodayHealthTitle,
                              style: ThemeUtil.p1,
                            ),
                          ),
                          const SizedBox(height: 10),
                          SizedBox(
                            width: 200,
                            child: Text(
                              textAlign: TextAlign.center,
                              strTodayHealthContent,
                              style: ThemeUtil.mp2.copyWith(fontSize: 12),
                            ),
                          ),
                        ],
                      ),

                      //环形图片
                      CustomPaint(
                        painter: CyclePainter(_days, ovulationImage: _ovulationImage),
                        size: const Size(240, 240),
                      ),

                      //顶部月经日图片
                      Container(
                        margin: const EdgeInsets.only(top: 6),
                        alignment: Alignment.topCenter,
                        width: 12,
                        height: 248,
                        child: const Image(
                          image: AssetImage(ImageRes.ic_cycle_menstruation_start),
                          width: 12,
                          height: 12,
                        ),
                      ),

                    ]),
              ),

              //女性健康类型设置
              JSWLine(
                clickable: false,
                margin: const EdgeInsets.only(left: 20.0, right: 10.0),
                children: [
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: 10,
                                height: 10,
                                decoration: const BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Color(ThemeUtil
                                      .primaryCalendarSelectValue),
                                ),
                              ),
                              const SizedBox(
                                height: 10.0,
                                width: 4.0,
                              ),
                              Text(
                                StringRes.menstrual_period,
                                textAlign: TextAlign.center,
                                style: ThemeUtil.p2.copyWith(
                                    fontSize: 10,
                                    color: const Color(
                                        ThemeUtil.primaryWhiteValue50)),
                              ),
                            ],
                          ),
                          Container(
                            margin: const EdgeInsets.only(top: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment:
                              CrossAxisAlignment.center,
                              children: <Widget>[
                                Container(
                                  width: 10,
                                  height: 10,
                                  decoration: const BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Color(ThemeUtil
                                        .primarMainPregnancyValue),
                                  ),
                                ),
                                const SizedBox(
                                  height: 10.0,
                                  width: 4.0,
                                ),
                                Text(
                                  StringRes.easy_pregnancy,
                                  textAlign: TextAlign.center,
                                  style: ThemeUtil.p2.copyWith(
                                      fontSize: 10,
                                      color: const Color(
                                          ThemeUtil.primaryWhiteValue50)),
                                ),
                              ],
                            ),
                          ),
                        ],
                      )),
                  const SizedBox(width: 10.0),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: 10,
                                height: 10,
                                decoration: const BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Color(
                                      ThemeUtil.primarFollicularValue),
                                ),
                              ),
                              const SizedBox(
                                height: 10.0,
                                width: 4.0,
                              ),
                              Text(
                                StringRes.follicular_phase,
                                textAlign: TextAlign.center,
                                style: ThemeUtil.p2.copyWith(
                                    fontSize: 10,
                                    color: const Color(
                                        ThemeUtil.primaryWhiteValue50)),
                              ),
                            ],
                          ),
                          Container(
                            margin: const EdgeInsets.only(top: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment:
                              CrossAxisAlignment.center,
                              children: <Widget>[
                                Image(
                                  image: AssetImage(
                                      ImageRes.ic_main_ovulation),
                                  width: 10,
                                  height: 10,
                                ),
                                const SizedBox(
                                  height: 10.0,
                                  width: 4.0,
                                ),
                                Text(
                                  StringRes.ovulation_day,
                                  textAlign: TextAlign.center,
                                  style: ThemeUtil.p2.copyWith(
                                      fontSize: 10,
                                      color: const Color(
                                          ThemeUtil.primaryWhiteValue50)),
                                ),
                              ],
                            ),
                          ),
                        ],
                      )),
                  const SizedBox(width: 10.0),
                  BaseViewItem(
                      weight: 1,
                      child: Column(
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Container(
                                width: 10,
                                height: 10,
                                decoration: const BoxDecoration(
                                  shape: BoxShape.circle,
                                  color:
                                  Color(ThemeUtil.primarLutealValue),
                                ),
                              ),
                              const SizedBox(
                                height: 10.0,
                                width: 4.0,
                              ),
                              Text(
                                StringRes.luteal_phase,
                                textAlign: TextAlign.center,
                                style: ThemeUtil.p2.copyWith(
                                    fontSize: 10,
                                    color: const Color(
                                        ThemeUtil.primaryWhiteValue50)),
                              ),
                            ],
                          ),
                          Container(
                            margin: const EdgeInsets.only(top: 12),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment:
                              CrossAxisAlignment.center,
                              children: <Widget>[
                                Container(
                                  width: 10,
                                  height: 10,
                                  decoration: const BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Color(ThemeUtil
                                        .primarMainPredictionValue),
                                  ),
                                ),
                                const SizedBox(
                                  height: 10.0,
                                  width: 4.0,
                                ),
                                Text(
                                  StringRes.prediction,
                                  textAlign: TextAlign.center,
                                  style: ThemeUtil.p2.copyWith(
                                      fontSize: 10,
                                      color: const Color(
                                          ThemeUtil.primaryWhiteValue50)),
                                ),
                              ],
                            ),
                          ),
                        ],
                      )),
                ],
              ),

              //经期设置
              EasyTouch(
                width: double.infinity,
                onPressed: () async {
                  Get.toNamed(PageIndex.menstrualSettingPage, arguments: {
                    "menstrualTime": _menstrualTime,
                    "cycleValue": _cycleValue,
                    "periodValue": _menstrualPeriodDays,
                    "regularly": _regularly,
                    "tracking": _tracking,
                  });
                },
                child: Container(
                    width: double.infinity,
                    margin: const EdgeInsets.only(
                        top: 24, left: 15, right: 15),
                    padding: const EdgeInsets.only(
                        top: 17, bottom: 17, left: 15, right: 15),
                    decoration: BoxDecoration(
                      color: Colors.white12,
                      borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          textAlign: TextAlign.left,
                          StringRes.menstrual_setting,
                          style:
                          ThemeUtil.p1.copyWith(fontFamily: 'Medium'),
                        ),
                        const Spacer(),
                        const Image(
                          image: AssetImage(ImageRes.ic_arrow_right),
                          width: 8,
                          height: 16,
                          fit: BoxFit.cover,
                        ),
                      ],
                    )),
              ),

              //今日提醒
              Container(
                  width: double.infinity,
                  margin:
                  const EdgeInsets.only(top: 10, left: 15, right: 15),
                  padding: const EdgeInsets.only(
                      top: 17, bottom: 13, left: 15, right: 15),
                  decoration: BoxDecoration(
                    color: Colors.white12,
                    borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        textAlign: TextAlign.left,
                        StringRes.today_reminder,
                        style:
                        ThemeUtil.p2.copyWith(fontFamily: 'Medium'),
                      ),
                      Container(
                          margin: const EdgeInsets.only(top: 2),
                          child: Text(
                            _todayReminder,
                            style: ThemeUtil.p2.copyWith(
                                fontSize: 13,
                                color: const Color(
                                    ThemeUtil.primaryWhiteValue50)),
                          )),
                    ],
                  )),

              //温度，心率，静息
              JSWLine(
                clickable: false,
                margin: const EdgeInsets.only(
                    top: 40, left: 20.0, right: 20.0),
                children: [
                  BaseViewItem(
                    weight: 1,
                    child: EasyTouch(
                      width: double.infinity,
                      onPressed: () async {
                        _selectChartType = 1;
                        setState(() {});
                      },
                      child: Column(
                        mainAxisAlignment:
                        MainAxisAlignment.start,
                        crossAxisAlignment:
                        CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            mainAxisAlignment:
                            MainAxisAlignment.start,
                            crossAxisAlignment:
                            CrossAxisAlignment.end,
                            children: [
                              Text(
                                _dayTemperature != 0.0
                                    ? _dayTemperature > 0 ? "+${_formatDouble(_dayTemperature)}" : _formatDouble(_dayTemperature)
                                    : "--",
                                style: ThemeUtil.h1
                                    .copyWith(fontSize: 20),
                              ),
                              const SizedBox(
                                width: 4,
                              ),
                              Text(
                                _tempType == 0 ? '℃' : '℉',
                                style: ThemeUtil.p2,
                              ),
                            ],
                          ),
                          Container(
                              margin: const EdgeInsets.only(
                                  top: 12, bottom: 8),
                              child: Text(
                                StringRes.skin_temperature,
                                style: ThemeUtil.p2,
                              )),
                          HorizontalLine(
                              dashedHeight: 2,
                              color: Color(_selectChartType == 1
                                  ? ThemeUtil.primaryBlueValue
                                  : ThemeUtil
                                  .primarTransparentValue)),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(width: 10.0),
                  BaseViewItem(
                    weight: 1,
                    child: EasyTouch(
                      width: double.infinity,
                      onPressed: () async {
                        _selectChartType = 2;
                        setState(() {});
                      },
                      child: Column(
                        mainAxisAlignment:
                        MainAxisAlignment.start,
                        crossAxisAlignment:
                        CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            mainAxisAlignment:
                            MainAxisAlignment.start,
                            crossAxisAlignment:
                            CrossAxisAlignment.center,
                            children: [
                              Text(
                                "${_dayHrv.toInt() == 0 ? "--" : _dayHrv.toInt()}",
                                style: ThemeUtil.h1
                                    .copyWith(fontSize: 20),
                              ),
                              const SizedBox(
                                width: 4,
                              ),
                              Text(
                                "ms",
                                style: ThemeUtil.p2,
                              ),
                            ],
                          ),
                          Container(
                              margin: const EdgeInsets.only(
                                  top: 12, bottom: 8),
                              child: Text(
                                StringRes.heart_rate_variability,
                                style: ThemeUtil.p2,
                              )),
                          HorizontalLine(
                              dashedHeight: 2,
                              color: Color(_selectChartType == 2
                                  ? ThemeUtil.primaryBlueValue
                                  : ThemeUtil
                                  .primarTransparentValue)),
                        ],
                      ),
                    ),
                  ),
                  const SizedBox(width: 10.0),
                  BaseViewItem(
                    weight: 1,
                    child: EasyTouch(
                      width: double.infinity,
                      onPressed: () async {
                        _selectChartType = 3;
                        setState(() {});
                      },
                      child: Column(
                        mainAxisAlignment:
                        MainAxisAlignment.start,
                        crossAxisAlignment:
                        CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            mainAxisAlignment:
                            MainAxisAlignment.start,
                            crossAxisAlignment:
                            CrossAxisAlignment.end,
                            children: [
                              Text(
                                "${_dayHr.toInt() == 0 ? "--" : _dayHr.toInt()}",
                                style: ThemeUtil.h1
                                    .copyWith(fontSize: 20),
                              ),
                              const SizedBox(
                                width: 4,
                              ),
                              Text(
                                "bmp",
                                style: ThemeUtil.p2,
                              ),
                            ],
                          ),
                          Container(
                              margin: const EdgeInsets.only(
                                  top: 12, bottom: 8),
                              child: Text(
                                StringRes.resting_heart_rate,
                                style: ThemeUtil.p2,
                              )),
                          HorizontalLine(
                              dashedHeight: 2,
                              color: Color(_selectChartType == 3
                                  ? ThemeUtil.primaryBlueValue
                                  : ThemeUtil
                                  .primarTransparentValue)),
                        ],
                      ),
                    ),
                  ),
                ],
              ),

              //统计图
              _buildBarChart(),

              //说明
              JSWLine(
                margin: const EdgeInsets.only(
                    top: 23, left: 20, right: 15, bottom: 50),
                children: [
                  BaseViewItem(
                      weight: 7,
                      child: Text(
                        textAlign: TextAlign.left,
                        StringRes.main_health_warning,
                        style: ThemeUtil.p2.copyWith(
                            fontSize: 12,
                            color: const Color(
                                ThemeUtil.primaryWhiteValue50)),
                      )),
                  BaseViewItem(
                      weight: 1,
                      child: IconButton(
                        icon: const ImageIcon(
                          AssetImage(ImageRes.ic_mian_warning),
                          size: 18,
                          color: Colors.white,
                        ),
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                        hoverColor: Colors.transparent,
                        onPressed: () {
                          //说明
                          Get.toNamed(PageIndex.explainSelectPage);
                        },
                      )),
                ],
              ),
            ],
          ),
        )
            : JSWBaseView(
          bodyColor: Colors.transparent,
          head: AppBar(
            elevation: 0.0,
            backgroundColor: Colors.transparent,
            title: EasyTouch(
              width: double.infinity,
              padding: const EdgeInsets.only(right: 55),
              child: Text(
                StringRes.women_cycle_title,
                textAlign: TextAlign.center,
                style: ThemeUtil.toolbar,
              ),
            ),
            leading: IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              hoverColor: Colors.transparent,
              icon: const Icon(
                Icons.arrow_back,
                color: Colors.white,
              ),
              onPressed: () {
                Native.backPressed();
              },
            ),
          ),
          body: Column(
            children: [
              //内容
              Container(
                  margin:
                  const EdgeInsets.only(top: 30, left: 20, right: 20),
                  child: Text(
                    textAlign: TextAlign.center,
                    StringRes.women_cycle_content,
                    style: ThemeUtil.h1.copyWith(fontSize: 22),
                  )),

              //提示
              Container(
                  margin:
                  const EdgeInsets.only(top: 10, left: 20, right: 20),
                  child: Text(
                    StringRes.women_cycle_tips,
                    textAlign: TextAlign.center,
                    style: ThemeUtil.p2.copyWith(
                        color:
                        const Color(ThemeUtil.primaryWhiteValue50)),
                  )),

              //周期选择器
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    margin: const EdgeInsets.only(top: 24),
                    height: 240,
                    width: 60,
                    child: ClickableListWheelScrollView(
                      scrollController: _scrollController,
                      itemHeight: _itemHeight,
                      itemCount: _items.length,
                      child: ListWheelScrollView.useDelegate(
                        controller: FixedExtentScrollController(
                            initialItem: _cycleValue),
                        itemExtent: _itemHeight,
                        physics: const FixedExtentScrollPhysics(),
                        overAndUnderCenterOpacity: 0.5,
                        perspective: 0.002,
                        onSelectedItemChanged: (index) {
                          _cycleValue = index;
                          _isNormalCycle.value =
                          (index > 3 && index < 21);
                        },
                        childDelegate: ListWheelChildBuilderDelegate(
                          builder: (context, index) =>
                              ValueListenableBuilder<bool>(
                                  valueListenable: _isNormalCycle,
                                  builder: (context, value, child) {
                                    return Text(_items[index].toString(),
                                        textAlign: TextAlign.center,
                                        style: _isNormalCycle.value
                                            ? ThemeUtil.p1
                                            : ThemeUtil.p1.copyWith(
                                            color: const Color(ThemeUtil
                                                .primaryYellowValue)));
                                  }),
                          childCount: _items.length,
                        ),
                      ),
                    ),
                  ),
                  ValueListenableBuilder<bool>(
                      valueListenable: _isNormalCycle,
                      builder: (context, value, child) {
                        return Text(StringRes.days,
                            textAlign: TextAlign.center,
                            style: _isNormalCycle.value
                                ? ThemeUtil.p1
                                : ThemeUtil.p1.copyWith(
                                color: const Color(
                                    ThemeUtil.primaryYellowValue)));
                      }),
                ],
              ),
            ],
          ),
          bottom: Container(
            margin: EdgeInsets.only(
                bottom: 30 + MediaQuery.of(context).viewPadding.bottom,
                left: 30,
                right: 30),
            child: //下一步按钮
            Container(
              height: 50,
              alignment: Alignment.center,
              decoration: ThemeUtil.themeConStyle,
              child: TextButton(
                style: ThemeUtil.themebtnStyle,
                onPressed: () async {
                  Get.toNamed(PageIndex.periodLengthPage, arguments: {
                    "isReset": false,
                    "cycleValue": _items[_cycleValue],
                    "periodValue": 5,
                  });
                },
                child: Text(StringRes.next_step,
                    textAlign: TextAlign.center, style: ThemeUtil.p2),
              ),
            ),
          ),
        )),
      ],
    );
  }

  Widget _buildTargetSetting() {
    return  JSWBaseView(
      bodyColor: Colors.transparent,
      head: AppBar(
        elevation: 0.0,
        backgroundColor: Colors.transparent,
        title: EasyTouch(
          width: double.infinity,
          padding: const EdgeInsets.only(right: 55),
          child: Text(
            StringRes.target,
            textAlign: TextAlign.center,
            style: ThemeUtil.toolbar,
          ),
        ),
        leading: IconButton(
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
          hoverColor: Colors.transparent,
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: () {
            Native.backPressed();
          },
        ),
      ),
      body: Column(
        children: [
          //内容
          Container(
              margin: const EdgeInsets.only(top: 30, left: 20, right: 20),
              child: Text(
                  textAlign: TextAlign.center,
                  StringRes.women_target_content,
                  style: ThemeUtil.h1.copyWith(fontSize: 20)
              )),

          //提示
          Container(
              margin: const EdgeInsets.only(top: 10, left: 30, right: 30),
              child: Text(
                StringRes.women_target_tips,
                textAlign: TextAlign.center,
                style: ThemeUtil.p2.copyWith(
                    color: const Color(ThemeUtil.primaryWhiteValue50)),
              )),
          //周期跟踪
          JSWLine(
            clickable: true,
            margin: const EdgeInsets.only(top: 30, left: 15, right: 15),
            padding: const EdgeInsets.only(
                top: 10, bottom: 10, left: 20, right: 12),
            decoration: BoxDecoration(
              color: Colors.white12,
              borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
              border: Border.all(
                  width: 1,
                  color:
                  _tracking == 1 ? Colors.white70 : Colors.transparent),
            ),
            onPressed: () {
              setState(() {
                _tracking = 1;
              });
            },
            children: [
              BaseViewItem(
                  weight: 5,
                  child: const Image(
                    image: AssetImage(ImageRes.ic_cycle_tracking),
                  )),
              BaseViewItem(weight: 1, child: Container()),
              BaseViewItem(
                weight: 25,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      textAlign: TextAlign.left,
                      StringRes.cycle_tracking_content,
                      style: ThemeUtil.p2.copyWith(fontFamily: 'Medium'),
                    ),
                    Container(
                        margin: const EdgeInsets.only(top: 2),
                        child: Text(
                          StringRes.cycle_tracking_tips,
                          style: ThemeUtil.p2.copyWith(
                              fontSize: 13,
                              color: const Color(
                                  ThemeUtil.primaryWhiteValue50)),
                        )),
                  ],
                ),
              )
            ],
          ),

          //受孕
          JSWLine(
            clickable: true,
            margin: const EdgeInsets.only(top: 15, left: 15, right: 15),
            padding: const EdgeInsets.only(
                top: 10, bottom: 10, left: 20, right: 12),
            decoration: BoxDecoration(
              color: Colors.white12,
              borderRadius: BorderRadius.circular(20.0), // 设置圆角半径
              border: Border.all(
                  width: 1,
                  color:
                  _tracking == 0 ? Colors.white70 : Colors.transparent),
            ),
            onPressed: () {
              setState(() {
                _tracking = 0;
              });
            },
            children: [
              BaseViewItem(
                  weight: 5,
                  child: const Image(
                    image: AssetImage(ImageRes.ic_women_conception),
                  )),
              BaseViewItem(weight: 1, child: Container()),
              BaseViewItem(
                weight: 25,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      textAlign: TextAlign.left,
                      StringRes.conception_content,
                      style: ThemeUtil.p2.copyWith(fontFamily: 'Medium'),
                    ),
                    Container(
                        margin: const EdgeInsets.only(top: 2),
                        child: Text(
                          StringRes.conception_tips,
                          style: ThemeUtil.p2.copyWith(
                              fontSize: 13,
                              color: const Color(
                                  ThemeUtil.primaryWhiteValue50)),
                        )),
                  ],
                ),
              )
            ],
          ),
        ],
      ),
      bottom: Container(
        margin: EdgeInsets.only(bottom: 30 + MediaQuery.of(context).viewPadding.bottom, left: 30, right: 30),
        child: //下一步按钮
        Container(
          height: 50,
          alignment: Alignment.center,
          decoration: ThemeUtil.themeConStyle,
          child: TextButton(
            style: ThemeUtil.themebtnStyle,
            onPressed: () async {
              if(_tracking == 0){
                Native.backPressed();
                Native.resetWomenConceptionData();
              }else{
                isTargetSetting = false;
                Native.setWomenPredictionData();
              }
            },
            child: Text(StringRes.confirm,
                textAlign: TextAlign.center, style: ThemeUtil.p2),
          ),
        ),
      ),
    );
  }

  Widget _buildBarChart() {
    DartLog.i(_tag, '_buildBarChart initState selectType:$_selectChartType}');
    //温度统计图
    if (_selectChartType == 1 && _cycleValue > 0 && _menstrualPeriodDays > 0 && _temperatureDataMap.isNotEmpty && _temperatureDataMap.length >= 25) {
      return DrawTempBarChart(
        menstrualTime: _menstrualTime,
        cycleValue: _cycleValue,
        menstrualPeriodDays: _menstrualPeriodDays,
        barDataMap: _temperatureDataMap,
        periodDataMap: _periodDataMap,
        onBarTap: (data) {
          DartLog.i(_tag, "温度统计图点击了事件 clicked: data=$data");
          _dayTemperature = data;
          setState(() {});
        },
      );
    }

    //心率变异性统计图
    if (_selectChartType == 2 && _cycleValue > 0 && _menstrualPeriodDays > 0 && _hrvDataMap.isNotEmpty) {
      return DrawHrvBarChart(
        menstrualTime: _menstrualTime,
        cycleValue: _cycleValue,
        menstrualPeriodDays: _menstrualPeriodDays,
        barDataMap: _hrvDataMap,
        periodDataMap: _periodDataMap,
        onBarTap: (data) {
          DartLog.i(_tag, "心率变异性统计图点击了事件 clicked: data=$data");
          _dayHrv = data;
          setState(() {});
        },
      );
    }

    //静息心率统计图
    if (_selectChartType == 3 && _cycleValue > 0 && _menstrualPeriodDays > 0 && _hrDataMap.isNotEmpty) {
      return DrawHrBarChart(
        menstrualTime: _menstrualTime,
        cycleValue: _cycleValue,
        menstrualPeriodDays: _menstrualPeriodDays,
        barDataMap: _hrDataMap,
        periodDataMap: _periodDataMap,
        onBarTap: (data) {
          DartLog.i(_tag, "静息心率统计图点击了事件 clicked: data=$data");
          _dayHr = data;
          setState(() {});
        },
      );
    }

    //数据空的统计图
    return const EmptyDrawBarChart();
  }

  ///获取今天的周期(1:月经期 2:卵泡期 3:易孕期(排卵期) 4:排卵日 5:黄体期 6:预测)
  int _getTodayFemaleCycle() {
    if (_menstrualTime <= 0) {
      _todayReminder = StringRes.menstrual_period_reminder;
      return 1;
    }
    if (_isOvulationDay(_todayDate)) {
      _todayReminder = StringRes.ovulation_day_reminder;
      return 4; //排卵日
    }
    int differenceDay = (((_todayDate.difference(_menstrualDateTime).inDays).abs()) % _cycleValue) + 1;
    DartLog.i(_tag, '今天和第一次月经相差多少天 differenceDay$differenceDay');
    if (differenceDay <= _menstrualPeriodDays) {
      _todayReminder = StringRes.menstrual_period_reminder;
      return 1; // 月经期
    } else if (differenceDay <= _menstrualPeriodDays + _follicularPhaseDays) {
      _todayReminder = StringRes.menstrual_period_reminder;
      return 2; // 卵泡期
    } else if (differenceDay <= _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays) {
      _todayReminder = StringRes.easy_pregnancy_reminder;
      return 3; // 易孕期
    } else if (differenceDay <=
        _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays + _lutealPhaseDays) {
      _todayReminder = StringRes.luteal_phase_reminder;
      return 5; // 黄体期
    } else {
      _todayReminder = StringRes.menstrual_period_reminder;
      return 6; // 预测
    }
  }

  ///获取当前日期的背景色
  int _getWeekBackgroundColor(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return ThemeUtil.primarTransparentValue;
    }
    if(_periodDataMap.isNotEmpty && _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null){
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if(type == 1 || type == 6 || type == 7){
        return ThemeUtil.primaryCalendarSelectValue;
      }
      if(type == 4){
        return ThemeUtil.primarOvulationValue;
      }
      if(type == 3 || type == 8 || type == 9){
        return ThemeUtil.primarPregnancyValue;
      }
      return ThemeUtil.primarTransparentValue;
    }
    if (_isOvulationDay(dateTime)) {
      return ThemeUtil.primarOvulationValue;
    }
    int differenceDay = (((dateTime.difference(_menstrualDateTime).inDays).abs()) % _cycleValue) + 1;
    if (differenceDay <= _menstrualPeriodDays) {
      return ThemeUtil.primaryCalendarSelectValue; // 月经期
    }else if (differenceDay > _menstrualPeriodDays + _follicularPhaseDays && differenceDay <= _menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays) {
      return ThemeUtil.primarMainPregnancyValue; // 易孕期
    } else {
      return ThemeUtil.primarTransparentValue;
    }
  }

  ///获取今天是周期的第几天
  int _getDayByFemaleCycle() {
    if (_menstrualTime <= 0) {
      return 0;
    }
    int differenceDay =
        (((_todayDate.difference(_menstrualDateTime).inDays).abs()) %
                _cycleValue) +
            1;
    DartLog.i(_tag, '当前时间和末次月经时间相差天数：$differenceDay');
    switch (_todayFemaleCycle) {
      case 1:
        return differenceDay;
      case 2:
        return differenceDay - _menstrualPeriodDays;
      case 3:
        return differenceDay - (_menstrualPeriodDays + _follicularPhaseDays);
      case 4:
        return 0;
      case 5:
        return differenceDay -
            (_menstrualPeriodDays + _follicularPhaseDays + _easyPregnancyDays);
    }
    return differenceDay;
  }

  ///获取今天距离下一个周期多少天
  int _getDistanceFemaleCycle() {
    if (_menstrualTime <= 0) {
      return 0;
    }
    switch (_todayFemaleCycle) {
      case 1:
        return _menstrualPeriodDays - _dayByFemaleCycle;
      case 2:
        return _follicularPhaseDays - _dayByFemaleCycle;
      case 3:
        return _easyPregnancyDays - _dayByFemaleCycle;
      case 4:
        return 0;
      case 5:
        return _lutealPhaseDays - _dayByFemaleCycle;
    }
    return 0;
  }

  ///判断是否是预测经期
  bool _isDuringMenstrualPeriodDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if(_periodDataMap.isNotEmpty && _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)] != null){
      int type = _periodDataMap[DateFormat("yyyy-MM-dd").format(dateTime)]!;
      if(type == 2 || type == 5 || type == 8){
        return false;
      }
    }
    int differenceDay = (((dateTime.difference(_menstrualDateTime).inDays).abs()) % _cycleValue) + 1;
    if (differenceDay <= _menstrualPeriodDays && dateTime.millisecondsSinceEpoch > DateTime.now().millisecondsSinceEpoch) {
      return true; // 预测月经期
    }
    return false;
  }

  ///判断是否是排卵日
  bool _isOvulationDay(DateTime dateTime) {
    if (_menstrualTime <= 0) {
      return false;
    }
    if (!_isShowOvulation) {
      return false;
    }
    if (DateFormat("yyyy-MM-dd").format(_ovulationDateTime) ==
        DateFormat("yyyy-MM-dd").format(dateTime)) {
      return true;
    }
    int differenceDay = _calculateDaysDifference(_ovulationDateTime, dateTime);
    if (differenceDay != 0 && differenceDay % _cycleValue == 0) {
      return true;
    }
    return false;
  }

  /// 计算两个 DateTime 对象相差的天数
  int _calculateDaysDifference(DateTime startDate, DateTime endDate) {
    return (startDate.difference(endDate).inDays).abs();
  }

  /// 格式化double值：三位小数以上保留两位，否则保持原格式
  String _formatDouble(double value) {
    if (value == 0.0) {
      return "--";
    }
    String valueStr = value.toString();
    if (!valueStr.contains('.')) return valueStr;
    List<String> parts = valueStr.split('.');
    String fractional = parts[1];
    if (fractional.length >= 3) {
      String fixed = value.toStringAsFixed(2);
      fixed = fixed.replaceAll(RegExp(r'0+$'), ''); // 移除尾部零
      return fixed.replaceAll(RegExp(r'\.$'), ''); // 移除末尾小数点
    } else {
      valueStr = valueStr.replaceAll(RegExp(r'0+$'), '');
      return valueStr.replaceAll(RegExp(r'\.$'), '');
    }
  }
}
